package com.banmao.CarlCamp.Day09;

public class LC19 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return head;
        }

        // 投机取巧的方法，使用中间数组
        // ∵题目中说明节点数量最多 30
        ListNode[] array = new ListNode[30];
        ListNode cur = head;
        int len = 0;
        while (cur != null) {
            array[len++] = cur;
            cur = cur.next;
        }

        int index = len - n;
        // 当需要删除的位置在 0 的时候，返回 head 之后的节点即可
        if (index == 0) {
            return head.next;
        }
        ListNode pre = array[index - 1];
        ListNode del = array[index];
        pre.next = del.next;
        del.next = null;

        return head;
    }

    private static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
